package com.cbn.ibcp.common.thread;

import cn.hutool.core.collection.CollUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

public class ExecutorServiceUtil {

    public static ExecutorService orgCodeSelectExecutorService = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), 2 * Runtime.getRuntime().availableProcessors(), 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1000), new ThreadPoolExecutor.DiscardOldestPolicy());

    /**
     * 分省统计线程池
     */
    public static ExecutorService orgStatisticExecutorService = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors(), 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1000), new ThreadPoolExecutor.DiscardOldestPolicy());


    public static <T> List<T> execute(ExecutorService executorService, List<Callable<T>> callableList) {
        if (CollUtil.isEmpty(callableList)) {
            return null;
        }
        List<Future<T>> futureList = new ArrayList<>();
        callableList.forEach(callable -> futureList.add(executorService.submit(callable)));
        return futureList.stream().map(future -> {
            try {
                return future.get();
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());
    }

}
